package a;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class ImageViewer extends JFrame {
    private JLabel imageLabel;

    public ImageViewer() {
        super("图片查看器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        imageLabel = new JLabel();
        JScrollPane scrollPane = new JScrollPane(imageLabel);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu fileMenu = new JMenu("文件");
        menuBar.add(fileMenu);
        JMenuItem openItem = new JMenuItem("打开");
        fileMenu.add(openItem);
        openItem.addActionListener(new OpenFileListener());
        setSize(400, 300);
        setVisible(true);
    }

    private class OpenFileListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(ImageViewer.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                String name = chooser.getSelectedFile().getPath();
                ImageIcon icon = new ImageIcon(name);
                imageLabel.setIcon(icon);
                pack();
            }
        }
    }

    public static void main(String[] args) {
        new ImageViewer();
    }
}
